package sunyu.service.shiro.impl;

import com.github.pagehelper.ISelect;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import sunyu.mapper.shiro.ResourceMapper;
import sunyu.mapper.shiro.RoleMapper;
import sunyu.mapper.shiro.RoleResourceMapper;
import sunyu.mapper.shiro.pojo.Resource;
import sunyu.mapper.shiro.pojo.Role;
import sunyu.mapper.shiro.pojo.RoleResourceKey;
import sunyu.service.shiro.RoleService;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author 孙宇
 */
@Service("roleService")
public class RoleServiceImpl implements RoleService {

    @javax.annotation.Resource(name = "roleMapper")
    private RoleMapper roleMapper;

    @javax.annotation.Resource(name = "roleResourceMapper")
    private RoleResourceMapper roleResourceMapper;

    @javax.annotation.Resource(name = "resourceMapper")
    private ResourceMapper resourceMapper;


    @Override
    @Transactional
    public Boolean insert(Role role,
                          String resourceIds) {
        if (roleMapper.insertSelective(role) > 0) {
            updateRoleResource(role, resourceIds);
            return true;
        }
        return false;
    }

    /**
     * 将角色与资源关联
     *
     * @param role
     * @param resourceIds
     */
    private void updateRoleResource(final Role role,
                                    String resourceIds) {
        deleteRoleResourceByRoleId(role.getId());

        if (StringUtils.isNotBlank(resourceIds)) {
            for (String resourceId : resourceIds.split(",")) {
                RoleResourceKey rr = new RoleResourceKey();
                rr.setRoleId(role.getId());
                rr.setResourceId(resourceId);
                roleResourceMapper.insert(rr);
            }
        }
    }

    @Override
    @Transactional
    public Boolean delete(String id) {
        deleteRoleResourceByRoleId(id);

        if (roleMapper.deleteByPrimaryKey(id) > 0) {
            return true;
        }
        return false;
    }

    /**
     * 根据角色id删除角色与资源的关联关系
     *
     * @param id
     */
    private void deleteRoleResourceByRoleId(final String id) {
        Map<String, Object> params = new HashMap<String, Object>() {{
            put("roleId", id);
        }};
        roleResourceMapper.delete(params);//先删除当前角色的所有资源关联
    }

    @Override
    public List<Role> select(Page page,
                             Map<String, Object> params) {
        if (page != null) {
            PageHelper.startPage(page.getPageNum(), page.getPageSize(), page.isCount());
            PageHelper.orderBy(page.getOrderBy());
        }
        return roleMapper.select(params);
    }

    @Override
    public Long count(Map<String, Object> params) {
        return PageHelper.count(new ISelect() {
            @Override
            public void doSelect() {
                roleMapper.select(params);
            }
        });
    }

    @Override
    @Transactional
    public Boolean update(Role role,
                          String resourceIds) {
        updateRoleResource(role, resourceIds);

        if (roleMapper.updateByPrimaryKeySelective(role) > 0) {
            return true;
        }
        return false;
    }

    @Override
    public Role selectById(String id) {
        return roleMapper.selectByPrimaryKey(id);
    }

    /**
     * 由于前台需要，这里返回的格式是  ['','']
     *
     * @param id
     *
     * @return
     */
    @Override
    public String getResourceIds(String id) {
        String resourceIds = "[";
        Map<String, Object> params = new HashMap<String, Object>() {{
            put("roleId", id);
        }};
        List<RoleResourceKey> l = roleResourceMapper.select(params);
        if (l != null && l.size() > 0) {
            for (int i = 0; i < l.size(); i++) {
                if (i > 0) {
                    resourceIds += ",";
                }
                resourceIds += "'" + l.get(i).getResourceId() + "'";
            }
        }
        return resourceIds + "]";
    }

    @Override
    public List<Resource> getResources(String roleId) {
        Map<String, Object> params = new HashMap<String, Object>() {{
            put("roleId", roleId);
        }};
        List<RoleResourceKey> rrs = roleResourceMapper.select(params);
        if (rrs != null && rrs.size() > 0) {
            List<Resource> resources = new ArrayList<>();
            for (RoleResourceKey rr : rrs) {
                resources.add(resourceMapper.selectByPrimaryKey(rr.getResourceId()));
            }
            return resources;
        }
        return null;
    }


}
